from flask import render_template, jsonify, g, request, current_app, redirect, abort

from info import db, constants
from info.models import User, Category, News
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import user_blue


@user_blue.route('/info')
@user_login_data
def get_user_info():
    user = g.user
    if not user:
        return redirect('/')
    data = {
        "user": user.to_dict(),
    }
    return render_template("news/user.html", data=data)


@user_blue.route('/base_info', methods=["GET", "POST"])
@user_login_data
def base_info():
    user = g.user
    if request.method == "GET":
        return render_template('news/user_base_info.html', data={"user": user.to_dict()})
    
    if not user:
        return jsonify(errno=RET.SERVERERR, errmsg="用户未登录")
    
    params_dict = request.json
    nick_name = params_dict.get('nick_name')
    signature = params_dict.get('signature')
    gender = params_dict.get("gender")
    
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    
    if gender not in ["MAN", "WOMAN"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    
    user.nick_name = nick_name
    user.gender = gender
    user.signature = signature
    
    try:
        db.session.commit()
    
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify("")
    
    return jsonify(errno=RET.OK, errmsg="更新成功")


@user_blue.route('/pic_info', methods=["GET", "POST"])
@user_login_data
def pic_info():
    user = g.user
    if request.method == "GET":
        return render_template('news/user_pic_info.html', data={"user": user.to_dict()})
    if not user:
        return jsonify(errno=RET.SERVERERR, errmsg="用户未登录")
    try:
        avatar_file = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="读取失败")
    
    try:
        avatar_url = storage(avatar_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="上传失败")
    
    user.avatar_url = avatar_url
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存失败")
    return jsonify(errno=RET.OK, errmsg="上传成功", data={
        "avatar_url": constants.QINIU_DOMIN_PREFIX + avatar_url
    })


@user_blue.route('/pass_info', methods=["GET", "POST"])
@user_login_data
def pass_info():
    user = g.user
    if request.method == "GET":
        return render_template('news/user_pass_info.html')
    
    if not user:
        return jsonify(errno=RET.SERVERERR, errmsg="用户未登录")
    
    param_dict = request.json
    old_password = param_dict.get("old_password")
    new_password = param_dict.get("new_password")
    # password_new = param_dict.get("password")
    
    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="原密码错误")
    
    user.password = new_password
    
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="密码保存失败")
    
    return jsonify(errno=RET.OK, errmsg="修改密码成功")


@user_blue.route('/collection')
@user_login_data
def user_collection():
    user = g.user
    if not user:
        return jsonify(errno=RET.PARAMERR, errmsg="用户未登录")
    
    p = request.args.get('p')
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
        # return jsonify(errno = RET.PARAMERR,errmsg="参数错误")
    collections = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.collection_news.paginate(p, constants.ADMIN_USER_PAGE_MAX_COUNT, False)
        collections = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="数据查询失败")
    
    collections_dict_li = []
    for collection in collections:
        collections_dict_li.append(collection.to_basic_dict())
    
    data = {
        "collections": collections_dict_li
    }
    
    return render_template('news/user_collection.html', data=data)


@user_blue.route('/news_release', methods=["GET", "POST"])
@user_login_data
def news_release():
    user = g.user
    if not user:
        return jsonify(errno=RET.PARAMERR, errmsg="用户未登录")
    if request.method == "GET":
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")
        category_dict_li = []
        
        for category in categories:
            category_dict_li.append(category.to_dict())
        
        data = {
            "categories": category_dict_li
        }
        return render_template('news/user_news_release.html', data=data)
    else:
        
        title = request.form.get("title")
        category_id = request.form.get("category_id")
        digest = request.form.get("digest")
        index_image = request.files.get("index_image")
        content = request.form.get("content")
        
        if not all([title, category_id, digest, index_image, content]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

        if index_image:
            try:
                index_image = index_image.read()
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
            
            try:
                key = storage(index_image)
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")
        
        news = News()
        news.title = title
        news.digest = digest
        news.source = "个人发布"
        news.content = content
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
        news.category_id = category_id
        news.user_id = g.user.id
        news.status = 1
        try:
            db.session.add(news)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg="保存数据失败")
        
        return jsonify(errno=RET.OK, errmsg="发布成功，等待审核")


@user_blue.route('news_list')
@user_login_data
def news_list():
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    
    user = g.user
    news_li = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
    
    news_dict_li = []
    
    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())
    data = {"news_list": news_dict_li, "total_page": total_page, "current_page": current_page}
    return render_template('news/user_news_list.html', data=data)


@user_blue.route('/user_follow')
@user_login_data
def user_follow():
    user = g.user
    
    if not user:
        return jsonify(errno=RET.SERVERERR, errmsg="用户未登录")
    
    p = request.args.get("p", 1)
    
    from flask import current_app
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    
    follows = []
    
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
        
        follows = paginate.items
        
        current_app = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="数据查询失败")
    
    user_dict_li = []
    
    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())
    data = {"users": user_dict_li, "total_page": total_page, "current_page": current_page}
    return render_template('news/user_follow.html', data=data)


@user_blue.route('/other_info')
@user_login_data
def other_info():
    user = g.user
    
    if not user:
        return jsonify(errno=RET.SERVERERR, errmsg="用户未登录")
    
    user_id = request.args.get("user_id")
    if not user_id:
        abort(404)
    
    other = None
    try:
        other = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
    if not other:
        abort(404)
    
    is_followed = False
    if g.user:
        if other.followers.filter(User.id == user.id).count() > 0:
            is_followed = True
    
    data = {
        "user_info": user.to_dict(),
        "other_info": other.to_dict(),
        "is_followed": is_followed
    }
    return render_template('news/other.html', data=data)


@user_blue.route('/other_news_list')
def other_news_list():
    p = request.args.get("p", 1)
    user_id = request.args.get("user_id")
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    
    if not all([p, user_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    
    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    
    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")
    
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
        news_li = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    
    news_dict_li = []
    
    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())
    data = {"news_list": news_dict_li, "total_page": total_page, "current_page": current_page}
    return jsonify(errno=RET.OK, errmsg="OK", data=data)
